package com.study.scala

object MatchDemo {

  def main(args: Array[String]): Unit = {

    normalMatch("a")
    // 多条件匹配
    normalMatch("f", "c")
    // 数组匹配
    arrayMatch(Array("c", "d"))
    // List匹配
    listMatch(List("a", "b"))
    // 类型匹配
    typeMatch(Map("a" -> "1"))
    // class 匹配
    classMatch(Teacher("zhang", 40))
  }

  def normalMatch(s: String): Unit = {
    s match {
      case "a" => println("match a")
      case _ => println("not match a")
    }
  }

  def normalMatch(s: String, t: String): Unit = {
    s match {
      case "a" => println("match a")
      case "b" => println("match b")
      case _ if (t == "c") => println("match c")
      case _ => println("match other")
    }
  }

  def arrayMatch(array: Array[String]): Unit = {
    array match {
      case Array("a") => println("Array match: a")
      case Array(x, y) => println("Array match: " + x + " and " + y)
      case Array("a", _*) => println("Array match: a and any other")
      case _ => println("Array match: other")
    }
  }

  def listMatch(list: List[String]): Unit = {
    list match {
      case "a" :: Nil => println("List match: only a")
      case x :: y :: Nil => println("List match: " + x + " and " + y)
      case "a" :: tail => println("List match: a and any other")
      case _ => println("List match: other")
    }
  }

  def typeMatch(obj: Any): Unit = {
    obj match {
      case x: Int => println("Type match: Int")
      case x: String => println("Type match: String")
      case x: Map[_, _] => println("Type match: Map")
      case _ => println("Type match: other")
    }
  }

  def classMatch(p: Person): Unit = {
    p match {
      case Student(name, no) => println("Student name:" + name + " and no:" + no)
      case Teacher(name, age) => println("Teacher name:" + name + " and age:" + age)
      case _ => println("Other person")
    }
  }

  class Person

  case class Student(name: String, no: Long) extends Person

  case class Teacher(name: String, age: Int) extends Person

  case class Other() extends Person

}
